const log4js      = require('../../data/log');
const logger      = log4js.getLogger('info');
const constants   = require('../../data/constants');
const channelModel= require('../../model/channel');
const server      = require('../../sip/server');
const mediaserverModel = require('../../model/mediaserver');
const mediaCtrl   = require('./media');
const deviceModel = require('../../model/device');
const alertModel  = require('../../model/alerts');
const format      = require('string-format');
const basectrl    = require('./basectrl');
const _ = require('lodash');

var path    = require("path");
var fs      = require("fs");
/**
 * 子通道
 */
let Channel = {
    geturl:async function(parentid, deviceid, types){
        //TODO: 这里临时写死
        // 获取 device 信息
        const device =await deviceModel.getDeviceByDeviceId(parentid);
        let server_id;
        if(device && device.server_id){
            server_id = device.server_id;
        }else{
            server_id = 1;
        }
        let host = await mediaserverModel.getInfoById(server_id);

        let str;
        switch(types){
            case 'hls':
                str = format('{url}rtp/v_{parentid}_{channelid}/hls.m3u8',Object.assign({parentid: parentid, channelid: deviceid}, host));
                break;
            case 'hlsTls':
                str = format('{urlTls}rtp/v_{parentid}_{channelid}/hls.m3u8',Object.assign({parentid: parentid, channelid: deviceid}, host));
                break;
            case 'local':
                str = format('{rtmp_snap}rtp/v_{parentid}_{channelid}',Object.assign({parentid: parentid, channelid: deviceid}, host));
                break;
            case 'flv':
                str = format('{url}rtp/v_{parentid}_{channelid}.flv',Object.assign({parentid: parentid, channelid: deviceid}, host));
                break;
            case 'flvTls':
                str = format('{urlTls}rtp/v_{parentid}_{channelid}.flv',Object.assign({parentid: parentid, channelid: deviceid}, host));
                break;
            case 'rtmp_snap':
                str = format('{rtmp_snap}rtp/v_{parentid}_{channelid}',Object.assign({parentid: parentid, channelid: deviceid}, host));
                break;
            default:
                str = format('{rtmp}rtp/v_{parentid}_{channelid}',Object.assign({parentid: parentid, channelid: deviceid}, host));
                break;
        }
        return str;
    },
    list:async function(req,res){
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        channelModel.list(req.query.account).then(async (rows) => {
            // TODO:生成 hls 地址
            let handleRows=[];

            for(var i in rows){
                //TODO: 海康大华的，如果通道大于1，那deviceid和parentid相等就不能用
                // 但JCO的设备，通道等于2时, deviceid和parentid相等是能用的
                if(rows.length>2 && rows[i].deviceid == rows[i].parentid){
                    // nvr 的这个通道不用
                    continue;
                }

                rows[i].hls     = await Channel.geturl(rows[i].parentid,rows[i].deviceid,'hls');
                rows[i].hlsTls  = await Channel.geturl(rows[i].parentid,rows[i].deviceid,'hlsTls');
                rows[i].rtmp    = await Channel.geturl(rows[i].parentid,rows[i].deviceid,'rtmp');
                rows[i].flv     = await Channel.geturl(rows[i].parentid,rows[i].deviceid,'flv');
                rows[i].flvTls  = await Channel.geturl(rows[i].parentid,rows[i].deviceid,'flvTls');
                handleRows.push(rows[i]);
            }
            // 处理逻辑 ...
            let ret =Object.assign(constants.httpCode.OK , {data:{items:handleRows,total:handleRows.length}});
            res.send(ret);
        }).catch((err) => {
            logger.error(err);
        });
    },
    // 发停止播放指令
    bye:function(req,res){
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        logger.log('bye req',req.query);
        let deviceid = req.query.deviceid;
        let channel  = req.query.channel;
        server.bye(deviceid,channel,(ret)=>{
            if(ret){
                res.send({'code':0,'msg':'success'});
            }else{
                res.send({'code':1,'msg':'通道未注册成功'});
            }
        })
    },
    // 截屏
    snap:function(req,res){
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        let deviceid = req.query.deviceid;
        let channel  = req.query.channel;
        let url = Channel.geturl(deviceid,channel,'local');

        mediaCtrl.snap(url,deviceid,channel).then((ret)=>{
            
            channelModel.updateSnap(ret.toString(), deviceid,channel).then(()=>{
                res.send(Object.assign(constants.httpCode.OK,{data:{}}));
            }).catch(()=>{
                res.send(Object.assign(constants.httpCode.ILLEGAL_PARAM,{data:{}}));
            })
            
        }).catch((err) => {
            logger.error(err);
        });
    },
    registry:function(req,res){
        if(!basectrl.hasLogin(req, res)){
            return;
        }
        let data = constants.registry;
        res.send(Object.assign(constants.httpCode.OK,{data:data}));
    }

};
module.exports=Channel;
